<script setup lang="ts">
import { ref } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import IconifyIcon from "@iconify-icons/ep/cloudy";
import { downloadByUrl, deviceDetection } from "@pureadmin/utils";
import * as XLSX from 'xlsx';
// 声明 props 类型
export interface FormProps {
  formInline: {
    user: string;
    region: string;
    id: string;
    template_url: string;
    dataList: object;
    checkCond: object;//检查字段，stateList.value,logisticsList.value,goodsOptionList.value
    export_field: object;
  };
}

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({ user: "", region: "",dataList:[[]] })
});

const newFormInline = ref(props.formInline);

// 以二进制读取文件
const readFile = (file: any) => {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = (e: any) => {
      resolve(e.target.result);
    };
  });
};
const downTemplate = () => {
  downloadByUrl(newFormInline.value.template_url)
  // window.open(newFormInline.value.template_url, '_blank')
};

const handleChange: UploadProps["onChange"] = async (uploadFile) => {
  //上传的文件
  let file = uploadFile.raw;
  if (!file) return;
  //读取上传的excel中的数据
  let data: any = await readFile(file);
  let workbook = XLSX.read(data, { type: "binary" ,raw: true, cellDates: true, dateNF: "yyyy/mm/dd"});
  //这里拿的是excel中第一个sheet表的数据
  const worksheet = workbook.Sheets[workbook.SheetNames[0]];
  // 把数据转化为json格式
  data = XLSX.utils.sheet_to_json(worksheet);

  //删掉示例那一行的数据
  data.shift();
// 为每个用户添加 isActive 属性

  if(data.length==0){
    return message(`excel中没有数据`, { type: "warning" });
  }else{
    data[0]['轮询跟进人'] = data[0]['轮询跟进人']||'-';
    data[0]['轮询情况'] = data[0]['轮询情况']||'-';
  }
  newFormInline.value.dataList = markDuplicates(data);
};

function markDuplicates(arr) {
  const seen = new Map();
  return arr.filter(x=>x.Email!=''&&x.Email!=undefined).map(item => {
    const value = `${item['Email']}:${item['电话']}`;
    const isDuplicate = seen.has(value);
    if(isDuplicate){
      return {'状态检查': '重复数据',...item};
    }else if(item['Email']=='' ||item['Email'] == undefined){
      return {'状态检查': '客户邮箱为空',...item};
    }else{
      let txt = '数据检查正常';//checkCond://检查字段，stateList.value,logisticsList.value,goodsOptionList.value
      const findSales = newFormInline.value.checkCond[0].find(x=>x.username.toUpperCase()==item['归属人'].toUpperCase())
      const findSales2 = newFormInline.value.checkCond[0].find(x=>x.username.toUpperCase()==item['轮询跟进人'])
      const Groups = ['A','B','C','D','E','F','G','H','I','J','K','S',]
      const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      item['Email'] = item['Email'].trim();
      if(findSales == undefined){
        txt = '没有找到归属人';
      }else if(findSales2 == undefined && item['轮询跟进人']!=''&&item['轮询跟进人']!='-'&&item['轮询跟进人']!=undefined){
        txt = '没有找到轮询跟进人';
      // }else if(!Groups.includes(item['组别'])){
        //txt = '没有找到小组';
      }else if(findSales?.dept.name !=item['组别']+'组'){
        txt = `用户${item['Name']}与${findSales?.dept.name}不符`;
      }else if(!regex.test(item['Email']) && item['Email'] !== '无'){//支持业绩无客户邮箱（邮箱字段为无，代表无邮箱，则不进行邮箱格式校验）
        txt = '客户邮箱有误';
      }else{
        seen.set(value, true);
      }
      item['own_saleman_id'] = findSales?.id||0;
      item['poll_saleman_id'] = findSales2?.id||0;
      item['dept_id'] = findSales?.dept?.id||0;
      return {'状态检查': txt,...item};
    }
  });
}

import {message} from "@/utils/message";
const cellFormat = function(row, column) {
  let data = row[column.property];
  if(column.property=='最后发货时间'){
    let data1: Date =  new Date(new Date(data).getTime() + 100000);

    // 获取日期组件
    const year = data1.getFullYear();
    const month = data1.getMonth() + 1; // 月份从0开始需+1
    const day = data1.getDate();
    if(!isNaN(year) ){
      data =  `${year}-${month}-${day}`;
    }
  }
  return data
}
const setWidth = function(item) {
  if(item=='Email')return 180;
  if(item=='组别')return 60;
  if(item=='Name')return 70;
  if(item=='SA')return 60;
  if(item=='归属人')return 70;
  if(item=='近期情况')return 180;
  if(item=='最后发货时间')return 100;
  return 100;
}

</script>

<template>
  <el-form :model="newFormInline" label-width="80px" label-position="left">
    <el-form-item label="第一步:" style="margin-bottom: 10px;">
      <el-link type="primary" @click="downTemplate">下载模板</el-link>
    </el-form-item>
    <el-form-item label="第二步:" style="margin-bottom: 10px;">
      <el-upload :show-file-list="false" action="#" :auto-upload="false" accept=".xls,.csv,.xlsx" :on-change="handleChange" :multiple="false">
        <el-button type="primary" size="small" :icon="useRenderIcon(IconifyIcon)">导入数据(1M以内)</el-button>
      </el-upload>
    </el-form-item>

    <el-table v-if="newFormInline.dataList" :data="newFormInline.dataList" style="width: 100%" size="small">
      <template v-if="newFormInline.dataList.length>0" v-for="item in Object.keys(newFormInline.dataList[0])">
        <el-table-column v-if="item =='状态检查'" label="状态检查" width="120">
          <template #default="{ row, $index }">
            <span v-if="row['状态检查'] =='数据检查正常'||row['状态检查'] =='ok'" style="color:green">{{row['状态检查']}}</span>
            <span v-else style="color:red">{{row['状态检查']}}</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip :prop="item" :label="item" :width="setWidth(item)"
                         v-else-if="!['ID','状态检查','sales_id','dept_id','customer_type','customer_source'].includes(item)"
                         :formatter="cellFormat" />
      </template>
    </el-table>
  </el-form>
</template>
